import React from 'react';
import {render} from 'react-dom';
import PageTile from 'component/page-title/index.jsx';
//引入通用列表组件
import TableList from 'tool/table-list/index.jsx';
//引入封装的分页组件
import Pagination from 'tool/pagination.jsx';
import Tool from  'tool/tool.jsx';
import User from  'service/user-service.jsx';
const _req = new Tool();
const _user = new User();


class UserList extends React.Component{
  constructor(props){
   super(props);
   //要给list初始化成数组，不然不能调用map
   this.state={
     list: [],
     pageNum: 1
   }
   this.loadUserList = this.loadUserList.bind(this);
 }
 componentDidMount(){
   this.loadUserList();
 }
 //获取用户列表
 loadUserList(){
     _user.getUserList(this.state.pageNum).then(res => {
        this.setState(res);
      },errMsg => {
         this.setState({
           list: []
         })
         _req.errorTips(errMsg);
     });
 }
 //页数改变发生改变时,修改当前页,setState是异步函数
 onPageNumChange(Num){
  this.setState({
    pageNum: Num
  },() => {
    this.loadUserList();
  })
 }
 render(){
    return(
       <div id="page-wrapper">
         <PageTile title='用户列表'/>
         <TableList tableHeaders={['ID','用户名','邮箱','电话','注册时间']}>
                {
                 this.state.list.map((user,index)=>{
                    return(
                          <tr key={index}>
                              <td>{user.id}</td>
                              <td>{user.username}</td>
                              <td>{user.email}</td>
                              <td>{user.phone}</td>
                              <td>{new Date(user.createTime).toLocaleString()}</td>
                          </tr>
                        )
                   })
                }
         </TableList>
         <Pagination current={this.state.pageNum} total={this.state.total}
                     onChange={pageNum=> this.onPageNumChange(pageNum)}/>
       </div>
    );
  }
}
export default UserList;